package com.example.tnot.Teacher.ActivityConfig;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;

import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.OnApplyWindowInsetsListener;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.navigation.NavController;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.example.tnot.R;
import com.example.tnot.Teacher.ActivityConfig.adapter.ViewPagerAdapter;
import com.example.tnot.Teacher.BaseFragment.BaseBackFragment;
import com.example.tnot.Teacher.Homepart.Container.HomeFragment;
import com.example.tnot.Teacher.MinePart.container.mineContainerFragment;
import com.example.tnot.Teacher.TeacherLiveActivity;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class TeacherHomeActivity extends AppCompatActivity {
    ViewPager2 vp_MainPage;
    BottomNavigationView nav_bottom;
    ViewPagerAdapter viewPagerAdapter;

    private ViewPager2 viewPager;
    private OnBackPressedCallback onBackPressedCallback;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_teacher_home);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_teacher), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        vp_MainPage = this.findViewById(R.id.viewpager_MainPager);
        //设置ViewPager2（ViewPager_MainPage）的适配器
        viewPagerAdapter = new ViewPagerAdapter(this);
        vp_MainPage.setAdapter(viewPagerAdapter);

        // 确保ViewPager2只预加载相邻页面以优化性能
        vp_MainPage.setOffscreenPageLimit(3);

        // 联动ViewPager2和BottomNavigationView
        vp_MainPage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                // 更新底部导航选中项
                nav_bottom.getMenu().getItem(position).setChecked(true);
//               //如果在CourseFragment页面就立马启动悬浮窗，不在CourseFragment页面就立马隐藏悬浮窗
//                if (position == 1) {
//                    // 发送广播或直接控制服务显示悬浮窗
//                    Intent intent = new Intent("com.example.tnot.Course.ShowFloatWindow");
//                    LocalBroadcastManager.getInstance(TeacherHomeActivity.this).sendBroadcast(intent);
//                } else {
//                    // 发送广播或直接控制服务隐藏悬浮窗
//                    Intent intent = new Intent("com.example.tnot.Course.HideFloatWindow");
//                    LocalBroadcastManager.getInstance(TeacherHomeActivity.this).sendBroadcast(intent);
//                }
            }
        });
        //设置底部导航栏的选中监听
        nav_bottom = findViewById(R.id.nav_bottom);
        nav_bottom.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.menu_home) {
                vp_MainPage.setCurrentItem(0);
            } else if (itemId == R.id.menu_course) {
                vp_MainPage.setCurrentItem(1);
            } else if (itemId == R.id.menu_message) {
                vp_MainPage.setCurrentItem(2);
            } else if (itemId == R.id.menu_me) {
                vp_MainPage.setCurrentItem(3);
            }
            return true;

        });
        // 注册返回键回调
        setupBackPressCallback();

//// 在Activity的onCreate方法中添加
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
//            // 处理刘海屏
//            WindowManager.LayoutParams params = getWindow().getAttributes();
//            params.layoutInDisplayCutoutMode =
//                    WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
//            getWindow().setAttributes(params);
//
//            // 设置全屏
//            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        }
//
//// 隐藏导航栏
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            getWindow().getDecorView().setSystemUiVisibility(
//                    View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
//                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
//                            View.SYSTEM_UI_FLAG_FULLSCREEN |
//                            View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
//                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
//                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//            );
//        }
        //还未实现!!! 需求：在用户打开软件时就询问是否允许权限
//        checkAndRequestOverlayPermission();

    }

    private void setupBackPressCallback() {
        onBackPressedCallback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // 检查当前是否在ViewPager的主要页面
                showExitConfirmationDialog();
            }
        };
        getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback);
    }

    private void showExitConfirmationDialog() {
        new AlertDialog.Builder(this)
                .setTitle("退出应用")
                .setMessage("确定要退出应用吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 最小化应用而不是完全退出
                        moveTaskToBack(true);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(true)
                .show();
    }


    public void hideBottomNavigation() {
        if (nav_bottom != null && nav_bottom.getVisibility() != View.GONE) {
            nav_bottom.animate() //添加向左消失动画
                    .translationX(-nav_bottom.getWidth())
                    .setDuration(300)
                    .setInterpolator(new AccelerateDecelerateInterpolator())
                    .withEndAction(new Runnable() {
                        @Override
                        public void run() {
                            nav_bottom.setVisibility(View.GONE);
                        }
                    })
                    .start();
        }

    }

    public void showBottomNavigation() {
        if (nav_bottom != null && nav_bottom.getVisibility() != View.VISIBLE) {
            nav_bottom.setVisibility(View.VISIBLE);
            nav_bottom.animate()//添加向左返回动画
                    .translationX(0)
                    .setDuration(325)
                    .setInterpolator(new AccelerateDecelerateInterpolator())
                    .start();
        }
    }

    // 禁用ViewPager2的滑动
    public void disableViewPagerSwipe() {
        if (vp_MainPage != null) {
            vp_MainPage.setUserInputEnabled(false);
        }
    }

    // 启用ViewPager2的滑动
    public void enableViewPagerSwipe() {
        if (vp_MainPage != null) {
            vp_MainPage.setUserInputEnabled(true);
        }
    }


}